import { bindData, ifPlayerData, getData } from "../Data/dataBase";
import { playerExpData } from "../configData/playerExpData";

const {ccclass, property} = cc._decorator;

@ccclass
export default class headBar extends cc.Component {

    @property(cc.ProgressBar)
    hpBar:cc.ProgressBar = null;
    @property(cc.ProgressBar)
    expBar:cc.ProgressBar = null;
    @property(cc.Label)
    levelLabel:cc.Label = null;

    private _hp:number;
    private _maxHp:number;
    private _level :number;
    private _exp: number;

    onLoad() {
        bindData("PLAYER_DATA", "", this.initData.bind(this), this);
        bindData("PLAYER_DATA", "HP", this.onHpChange.bind(this), this);
        bindData("PLAYER_DATA", "LEVEL", this.onLevelChange.bind(this), this);
        bindData("PLAYER_DATA", "MAX_HP", this.onMaxHpChange.bind(this), this);
        bindData("PLAYER_DATA", "EXP", this.onExpChange.bind(this), this);
        this.initData(getData("PLAYER_DATA"));
    }

    initData(data:ifPlayerData){
        this._hp = data.hp;
        this._level = data.level;
        this._maxHp = data.maxHp;
        this._exp = data.exp;
        this.refreshHpBar();
        this.refreshLevel();
        this.refreshExpBar();
    }

    refreshHpBar(){
        this.hpBar.node.getComponent("aniProgress").play(this.hpBar.progress, this._hp / this._maxHp);
    }
    refreshLevel(){
        this.levelLabel.string = this._level.toString();
        var tween = new cc.Tween();
        tween.target(this.levelLabel.node)
            .to(0.1, {scale: 2.0, opacity:200}, null)
            .to(0.1, {scale: 1.0, opacity:255}, null)
            .start();
    }
    refreshExpBar(){
        var preNeedExp = playerExpData[this._level-1] != null ? playerExpData[this._level-1] : 0;
        var nextNeedExp = playerExpData[this._level] != null ? playerExpData[this._level] : 0;
        this.expBar.node.getComponent("aniProgress").play(this.expBar.progress, (this._exp - preNeedExp) / (nextNeedExp - preNeedExp));
    }

    onHpChange(hp:number){
        this._hp = hp;
        this.refreshHpBar();
    }
    onMaxHpChange(maxHp:number){
        this._maxHp = maxHp;
        this.refreshHpBar();
    }
    onLevelChange(level:number){
        this._level = level;
        this.refreshLevel();
        this.refreshExpBar();
    }
    onExpChange(exp:number){
        this._exp = exp;
        this.refreshExpBar();
    }
}
